<?php
//打印错误控制
ini_set("display_errors", "On");
error_reporting(E_ALL | E_STRICT);

use Phalcon\Loader;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Url;
use Phalcon\Mvc\Application;
use Phalcon\DI\FactoryDefault;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
use Phalcon\Session\Adapter\Files as Session;   //会话
use Phalcon\Mvc\Dispatcher;                     //监听
use Phalcon\Events\Manager as EventsManager;    //事件

try {

    // Register an autoloader
    $loader = new Loader();
    $loader->registerDirs(array(
        '../app/controllers/',
        '../app/models/',
        '../app/plugins'
    ))->register();

    // Create a DI
    $di = new FactoryDefault();

    // Setup the view component
    $di->set('view', function(){
        $view = new View();
        $view->setViewsDir('../app/views/');
        return $view;
    });

    // Setup a base URI so that all generated URIs
    $di->set('url', function(){
        $url = new UrlProvider();
        $url->setBaseUri('');
        return $url;
    });

    // Setup the database service
    $di->set('db', function(){
        return new DbAdapter(array(
            "host"     => "localhost",
            "username" => "root",
            "password" => "",
            "dbname"   => "blug",
            "charset"  => "utf8"
        ));
    });

    // Start the session the first time a component requests the session service
    $di->set('session', function() {
        $session = new Session();
        $session->start();
        return $session;
    });

    // 监听事件
    $di->set('dispatcher', function() {
        $eventsManager = new EventsManager;
        /**
         * Check if the user is allowed to access certain action using the SecurityPlugin
         */
        $eventsManager->attach('dispatch:beforeDispatch', new SecurityPlugin);
        /**
         * Handle exceptions and not-found exceptions using NotFoundPlugin
         */
        $eventsManager->attach('dispatch:beforeException', new NotFoundPlugin);
        $dispatcher = new Dispatcher;
        $dispatcher->setEventsManager($eventsManager);

        return $dispatcher;
    });

    // Handle the request
    $application = new Application($di);

    echo $application->handle()->getContent();

} catch(\Exception $e) {
     echo "PhalconException: ", $e->getMessage();
}
